package com.mlf.observer.demo02;

import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.Flow;

public class Book {
    private double price;
    private final SubmissionPublisher<PriceChangeEvent> pricePublisher = new SubmissionPublisher<>();

    public double getPrice() {
        return price;
    }
    public void setPrice(double newPrice) {
        double oldPrice = this.price;
        this.price = newPrice;
        // 发布包含新旧价格的事件对象
        pricePublisher.submit(new PriceChangeEvent(oldPrice, newPrice));
    }

    public void subscribe(Flow.Subscriber<PriceChangeEvent> subscriber) {
        pricePublisher.subscribe(subscriber);
    }

    public void  shutdown() {
        pricePublisher.close();
    }

    public static void main(String[] args)  throws InterruptedException{
        Book book = new Book();
        book.subscribe(new PriceSubscriber());

        book.setPrice(5999);
        book.setPrice(6999);

        // 等待异步处理完成
        Thread.sleep(1000*3);

        book.shutdown();
        System.out.println("程序结束");

    }
}
